package com.zx.练习题._2022面试题;

public class Demo9 {

    public static void main(String[] args) {
        int search = search(new int[]{-2, -1, 3}, 3);
        System.out.println(search);
    }

    public static int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        //保存结果
        int resIdx = -1;
        int len = nums.length;

        int begin = 0;
        int end = len;

        while (begin <= end) {
            int mid = (end + begin) / 2;

            if (nums[mid] == target) {
                resIdx = mid;
                break;
            }
            //判断左右
            if (nums[mid] < target) {
                // 目标值在右边
                begin = ++mid;
                end = end;
            } else {
                begin = begin;
                end = --mid;
            }

            if (begin == end) {
                break;
            }
        }

        return resIdx;
    }
}
